#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试页面分割功能
验证页面分割逻辑是否正确工作
"""

from config import Config


def test_page_separator_logic():
    """测试页面分割逻辑"""
    print("=== 测试页面分割功能逻辑 ===")

    # 模拟OCR数据
    mock_ocr_data = [
        {
            "账号": "42001865757053005729",
            "开户银行名称": "中国建设银行股份有限公司武汉梨园支行",
            "账户性质": "基本存款账户",
            "开户日期": "2015年03月06日",
            "账户状态": "正常",
            "销户日期": "",
            "来源文件": "湖北_账户开立清单.pdf",
            "来源页面": "湖北_账户开立清单_page-0001.pdf"
        },
        {
            "账号": "42001865757053005730",
            "开户银行名称": "中国工商银行股份有限公司武汉分行",
            "账户性质": "一般存款账户",
            "开户日期": "2016年05月15日",
            "账户状态": "正常",
            "销户日期": "",
            "来源文件": "湖北_账户开立清单.pdf",
            "来源页面": "湖北_账户开立清单_page-0001.pdf"
        },
        {
            "账号": "42001865757053005731",
            "开户银行名称": "中国农业银行股份有限公司武汉分行",
            "账户性质": "专用存款账户",
            "开户日期": "2017年08月20日",
            "账户状态": "正常",
            "销户日期": "",
            "来源文件": "湖北_账户开立清单.pdf",
            "来源页面": "湖北_账户开立清单_page-0002.pdf"
        },
        {
            "账号": "42001865757053005732",
            "开户银行名称": "中国银行股份有限公司武汉分行",
            "账户性质": "临时存款账户",
            "开户日期": "2018年12月10日",
            "账户状态": "撤销",
            "销户日期": "2020年01月15日",
            "来源文件": "川渝_重庆四季度开立清单.pdf",
            "来源页面": "川渝_重庆四季度开立清单_page-0001.pdf"
        }
    ]

    print("原始OCR数据:")
    for i, record in enumerate(mock_ocr_data, 1):
        print(f"{i}. 账号: {record['账号']}, 来源: {record['来源文件']} - {record['来源页面']}")

    print("\n" + "=" * 60)

    # 测试页面分割功能启用时的数据组织
    if Config.is_page_separator_enabled():
        print("页面分割功能已启用，模拟数据重组:")

        organized_data = []
        current_file = None
        current_page = None

        for record in mock_ocr_data:
            file_name = record.get('来源文件', '')
            page_name = record.get('来源页面', '')

            # 检查是否需要添加分割行
            if file_name != current_file or page_name != current_page:
                if organized_data:  # 不是第一条记录时才添加分割行
                    # 添加空行作为分割
                    separator_row = {}
                    for key in record.keys():
                        if key not in ['来源文件', '来源页面']:
                            separator_row[key] = ""
                    separator_row['来源文件'] = ""
                    separator_row['来源页面'] = ""
                    organized_data.append(separator_row)

                # 添加页面信息行
                page_info_row = {}
                for key in record.keys():
                    if key == '账号':
                        page_info_row[key] = Config.get_page_separator(file_name, page_name)
                    elif key not in ['来源文件', '来源页面']:
                        page_info_row[key] = ""
                    else:
                        page_info_row[key] = ""
                organized_data.append(page_info_row)

                current_file = file_name
                current_page = page_name

            # 添加实际数据记录
            organized_data.append(record)

        print("重组后的数据:")
        for i, record in enumerate(organized_data, 1):
            account = record.get('账号', '')
            if account.startswith('==='):
                print(f"{i}. [分割行] {account}")
            elif not account:
                print(f"{i}. [空行]")
            else:
                print(f"{i}. 账号: {account}, 银行: {record.get('开户银行名称', '')[:20]}...")
    else:
        print("页面分割功能已禁用，数据保持原样")


def test_page_groups():
    """测试页面分组逻辑"""
    print("\n=== 测试页面分组逻辑 ===")

    # 模拟差异数据
    mock_differences = [
        {"账号": "42001865757053005729", "差异": "Excel中未找到此账号"},
        {"账号": "42001865757053005730",
         "差异": [{"字段": "开户银行名称", "OCR值": "中国工商银行", "Excel值": "工商银行"}]},
        {"账号": "42001865757053005731", "差异": "Excel中未找到此账号"},
        {"账号": "42001865757053005732", "差异": [{"字段": "账户状态", "OCR值": "撤销", "Excel值": "正常"}]},
    ]

    # 模拟OCR数据（用于获取页面信息）
    mock_ocr_data = [
        {"账号": "42001865757053005729", "来源文件": "湖北_账户开立清单.pdf",
         "来源页面": "湖北_账户开立清单_page-0001.pdf"},
        {"账号": "42001865757053005730", "来源文件": "湖北_账户开立清单.pdf",
         "来源页面": "湖北_账户开立清单_page-0001.pdf"},
        {"账号": "42001865757053005731", "来源文件": "湖北_账户开立清单.pdf",
         "来源页面": "湖北_账户开立清单_page-0002.pdf"},
        {"账号": "42001865757053005732", "来源文件": "川渝_重庆四季度开立清单.pdf",
         "来源页面": "川渝_重庆四季度开立清单_page-0001.pdf"},
    ]

    if Config.is_page_separator_enabled():
        # 按页面分组差异数据
        page_groups = {}
        for diff in mock_differences:
            account_number = diff["账号"]
            # 查找对应的OCR记录以获取页面信息
            ocr_record = next(
                (record for record in mock_ocr_data if str(record.get("账号", "")).strip() == account_number), None)

            if ocr_record:
                file_name = ocr_record.get('来源文件', '未知文件')
                page_name = ocr_record.get('来源页面', '未知页面')
                page_key = f"{file_name}|{page_name}"

                if page_key not in page_groups:
                    page_groups[page_key] = []
                page_groups[page_key].append(diff)
            else:
                # 如果找不到OCR记录，放到默认组
                default_key = "未知文件|未知页面"
                if default_key not in page_groups:
                    page_groups[default_key] = []
                page_groups[default_key].append(diff)

        print("按页面分组的差异数据:")
        for page_key, page_diffs in page_groups.items():
            file_name, page_name = page_key.split('|', 1)
            separator = Config.get_page_separator(file_name, page_name)
            print(f"\n{separator}")
            for diff in page_diffs:
                print(f"  - 账号: {diff['账号']}, 差异类型: {type(diff['差异']).__name__}")
    else:
        print("页面分割功能已禁用，不进行分组")


def main():
    """主函数"""
    print("页面分割功能测试")
    print("=" * 60)

    # 显示当前配置
    print(f"当前页面分割功能状态: {'启用' if Config.is_page_separator_enabled() else '禁用'}")
    print(f"分割信息格式: {Config.PAGE_SEPARATOR_FORMAT}")
    print()

    # 测试页面分割逻辑
    test_page_separator_logic()

    # 测试页面分组逻辑
    test_page_groups()

    print("\n" + "=" * 60)
    print("测试完成！")
    print("如需修改配置，请编辑 config.py 文件中的 ENABLE_PAGE_SEPARATOR 设置")


if __name__ == "__main__":
    main()
